package com.diamondsys.embrapa;

import com.diamondsys.embrapa.util.JsfUtil;
import com.diamondsys.embrapa.util.JsfUtil.PersistAction;
import java.io.IOException;

import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.ejb.EJBException;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import org.primefaces.event.FileUploadEvent;

/**
 *
 * @author Rafael
 */
@Named("participanteEventoController")
@SessionScoped
public class ParticipanteEventoController implements Serializable {

    @EJB
    private com.diamondsys.embrapa.ParticipanteEventoFacade ejbFacade;
    private List<ParticipanteEvento> items = null;
    private ParticipanteEvento selected;
    private Integer eventoId;
    private JsfUtil jsftutil;

    /**
     *
     */
    public ParticipanteEventoController() {
        this.prepareCreate();
    }

    /**
     *
     * @return
     */
    public ParticipanteEvento getSelected() {
        return selected;
    }

    /**
     *
     * @param selected
     */
    public void setSelected(ParticipanteEvento selected) {
        this.selected = selected;
    }

    /**
     *
     */
    protected void setEmbeddableKeys() {
    }

    /**
     *
     */
    protected void initializeEmbeddableKey() {
        selected.setParticipanteEventoPK(new com.diamondsys.embrapa.ParticipanteEventoPK());
    }

    private ParticipanteEventoFacade getFacade() {
        return ejbFacade;
    }

    /**
     *
     * @return
     */
    public ParticipanteEvento prepareCreate() {
        selected = new ParticipanteEvento();
        initializeEmbeddableKey();
        return selected;
    }

    /**
     *
     */
    public void create() {
        persist(PersistAction.CREATE, ResourceBundle.getBundle("/Bundle").getString("ParticipanteEventoCreated"));
        if (!JsfUtil.isValidationFailed()) {
            items = null;    // Invalidate list of items to trigger re-query.
        }
    }

    /**
     *
     */
    public void update() {
        persist(PersistAction.UPDATE, ResourceBundle.getBundle("/Bundle").getString("ParticipanteEventoUpdated"));
    }

    /**
     *
     */
    public void destroy() {
        persist(PersistAction.DELETE, ResourceBundle.getBundle("/Bundle").getString("ParticipanteEventoDeleted"));
        if (!JsfUtil.isValidationFailed()) {
            selected = null; // Remove selection
            items = null;    // Invalidate list of items to trigger re-query.
        }
    }

    /**
     *
     * @return
     */
    public List<ParticipanteEvento> getItems() {
        if (items == null) {
            items = getFacade().findAll();
        }
        return items;
    }

    private void persist(PersistAction persistAction, String successMessage) {
        if (selected != null) {
            setEmbeddableKeys();
            try {
                if (persistAction != PersistAction.DELETE) {
                    getFacade().edit(selected);
                } else {
                    getFacade().remove(selected);
                }
                JsfUtil.addSuccessMessage(successMessage);
            } catch (EJBException ex) {
                String msg = "";
                Throwable cause = ex.getCause();
                if (cause != null) {
                    msg = cause.getLocalizedMessage();
                }
                if (msg.length() > 0) {
                    JsfUtil.addErrorMessage(msg);
                } else {
                    JsfUtil.addErrorMessage(ex, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
                }
            } catch (Exception ex) {
                Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
                JsfUtil.addErrorMessage(ex, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            }
        }
    }

    /**
     *
     * @param id
     * @return
     */
    public ParticipanteEvento getParticipanteEvento(com.diamondsys.embrapa.ParticipanteEventoPK id) {
        return getFacade().find(id);
    }

    /**
     *
     * @return
     */
    public List<ParticipanteEvento> getItemsAvailableSelectMany() {
        return getFacade().findAll();
    }

    /**
     *
     * @return
     */
    public List<ParticipanteEvento> getItemsAvailableSelectOne() {
        return getFacade().findAll();
    }

    public void handleFileUpload(FileUploadEvent event) {
        FacesMessage message;
        
        if (this.eventoId == null)
        {
            JsfUtil.addWarningMessage("Selectione um evento!");
            return;
        }
        try {
            String fileName = JsfUtil.copyFile(event.getFile().getFileName(), event.getFile().getInputstream());
            this.parseMap(JsfUtil.parseCSVLines(fileName));
            message = new FacesMessage("Arquivo importado com sucesso!", event.getFile().getFileName() + " foi importado!");
        } catch (IOException e) {
            message = new FacesMessage("Erro ao importar", e.getMessage());
        }
        FacesContext.getCurrentInstance().addMessage(null, message);
    }
    
    private void parseMap(List<String[]> list)
    {
        TbInstController clienteController = (TbInstController) FacesContext.getCurrentInstance().getApplication().getELResolver().
                getValue(FacesContext.getCurrentInstance().getELContext(), null, "tbInstController");
        
        TbInst cliente;
        int localEventId = this.eventoId;
                
        for(String[] item: list)
        {
            if (item.length >= 3 && item[2].contains("@"))
            {
                cliente = clienteController.getByEmail(item[2]);
                
                if (cliente == null)
                {             
                    cliente = new TbInst();
                    cliente.setNomFantasia(item[1]);
                    cliente.setDesEmail(item[2]);                    
                    
                    clienteController.prepareCreate();
                    cliente.setDatInclusao(new Date());
                    cliente.setDesInclusao(((Usuario)JsfUtil.GetSessionParameter("user")).getLogin());                    
                    clienteController.setSelected(cliente);
                    clienteController.create();
                    cliente = clienteController.getByEmail(item[2]);
                }
                
                if (cliente != null)
                {
                    this.prepareCreate();
                    ParticipanteEventoPK pPK = new ParticipanteEventoPK();
                    pPK.setSigifEventosintIdeventosint(localEventId);
                    pPK.setTbInstCodInstituicao(cliente.getCodInstituicao());
                    selected.setParticipanteEventoPK(pPK);
                    
                    try
                    {
                        getFacade().edit(selected);
                    }catch(Exception ex){}
                }
                
            }             
        }
    }        

    /**
     * @return the eventoId
     */
    public Integer getEventoId() {
        return eventoId;
    }

    /**
     * @param eventoId the eventoId to set
     */
    public void setEventoId(Integer eventoId) {
        this.eventoId = eventoId;
    }

    
        
    /**
     *
     */
    @FacesConverter(forClass = ParticipanteEvento.class)
    public static class ParticipanteEventoControllerConverter implements Converter {

        private static final String SEPARATOR = "#";
        private static final String SEPARATOR_ESCAPED = "\\#";

        /**
         *
         * @param facesContext
         * @param component
         * @param value
         * @return
         */
        @Override
        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            ParticipanteEventoController controller = (ParticipanteEventoController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "participanteEventoController");
            return controller.getParticipanteEvento(getKey(value));
        }

        com.diamondsys.embrapa.ParticipanteEventoPK getKey(String value) {
            com.diamondsys.embrapa.ParticipanteEventoPK key;
            String values[] = value.split(SEPARATOR_ESCAPED);
            key = new com.diamondsys.embrapa.ParticipanteEventoPK();
            key.setSigifEventosintIdeventosint(Integer.parseInt(values[0]));
            key.setTbInstCodInstituicao(Integer.parseInt(values[1]));
            return key;
        }

        String getStringKey(com.diamondsys.embrapa.ParticipanteEventoPK value) {
            StringBuilder sb = new StringBuilder();
            sb.append(value.getSigifEventosintIdeventosint());
            sb.append(SEPARATOR);
            sb.append(value.getTbInstCodInstituicao());
            return sb.toString();
        }

        /**
         *
         * @param facesContext
         * @param component
         * @param object
         * @return
         */
        @Override
        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof ParticipanteEvento) {
                ParticipanteEvento o = (ParticipanteEvento) object;
                return getStringKey(o.getParticipanteEventoPK());
            } else {
                Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "object {0} is of type {1}; expected type: {2}", new Object[]{object, object.getClass().getName(), ParticipanteEvento.class.getName()});
                return null;
            }
        }

    }

}
